<template>
  <div class="divBox">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form inline size="small" label-position="right" @submit.native.prevent>
          <el-form-item label="姓名：">
            <el-input
              v-model.trim="searchForm.name"
              @keyup.enter.native="handerSearch()"
              placeholder="请输入姓名"
              class="selWidth"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号：">
            <el-input
              v-model.trim="searchForm.phoneNumber"
              @keyup.enter.native="handerSearch()"
              placeholder="请输入手机号"
              class="selWidth"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input
              v-model.trim="searchForm.email"
              @keyup.enter.native="handerSearch()"
              placeholder="请输入邮箱"
              class="selWidth"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="审核状态：">
            <el-select
              v-model="searchForm.checkStatus"
              clearable
              class="selWidth"
              placeholder="请选择审核状态"
              @change="handerSearch"
            >
              <el-option :value="null" label="待审核"></el-option>
              <el-option :value="1" label="审核通过"></el-option>
              <el-option :value="0" label="审核拒绝"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="认证类型：">
            <el-select
              v-model="searchForm.applyTypeList"
              clearable
              class="selWidth"
              placeholder="请选择认证类型"
              @change="handerSearch"
            >
              <el-option :value="1" label="个人"></el-option>
              <el-option :value="2" label="企业"></el-option>
              <el-option :value="3" label="学生"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="handerSearch()">查询</el-button>
            <el-button size="small" @click="reset()">重置</el-button>
            <el-button
              type="success"
              size="small"
              :loading="exportLoading"
              @click="handleExport"
            >
              {{ exportLoading ? '导出中...' : '导出' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card mt14" :body-style="{ padding: '20px' }" shadow="never" :bordered="false">
      <el-table v-loading="listLoading" :data="listData.list" size="small" highlight-current-row class="mt20">
        <el-table-column prop="euserId" label="用户ID" min-width="80" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="phoneNumber" label="手机号" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="idCard" label="身份证号" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="companyName" label="企业名称" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="schoolName" label="学校名称" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="applyType" label="认证类型" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="getapplyTypeListType(scope.row.applyType)">
              {{ getapplyTypeListText(scope.row.applyType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="checkStatus" label="审核状态" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="getAuditStatusType(scope.row.checkStatus)">
              {{ getAuditStatusText(scope.row.checkStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkRemark" label="审核说明" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="applyTime" label="报名时间" min-width="150" />
        <el-table-column prop="createTime" label="创建时间" min-width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-dropdown @command="handleCommand" trigger="click">
              <span class="el-dropdown-link"> 更多<i class="el-icon-arrow-down el-icon--right"></i> </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{ action: 'detail', row: scope.row }">详情</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-divider direction="vertical"></el-divider>
            <a
              @click="handleAudit(scope.row)"
              :class="{ 'disabled-link': isAuditCompleted(scope.row.checkStatus) }"
              :style="{ cursor: isAuditCompleted(scope.row.checkStatus) ? 'not-allowed' : 'pointer' }"
              >审核</a
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="listPram.page"
        :page-sizes="constants.page.limit"
        :layout="constants.page.layout"
        :total="listData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 审核抽屉 -->
    <el-drawer
      :visible.sync="auditDialogVisible"
      :direction="direction"
      custom-class="demo-drawer"
      size="1000px"
      ref="drawer"
      class="infoBox"
      @close="closeAuditDialog"
    >
      <div v-loading="auditLoading" v-if="auditDialogVisible">
        <div class="detailHead">
          <div class="acea-row row-between headerBox">
            <div class="full">
              <div class="order_icon"><span class="iconfont icon-shenhe"></span></div>
              <div class="text">
                <div class="title">选手认证审核</div>
                <div>
                  <span class="mr20"
                    >审核状态：<span class="color-warning">{{ getAuditStatusText(auditForm.auditStatus) }}</span></span
                  >
                </div>
              </div>
            </div>
            <div class="acea-row justify-content">
              <el-button
                v-debounceClick="
                  () => {
                    submitReject();
                  }
                "
                style="margin-left: 0"
                :loading="auditLoading"
                >{{ auditLoading ? '提交中 ...' : '审核拒绝' }}</el-button
              >
              <el-button
                type="primary"
                v-debounceClick="
                  () => {
                    submitPass();
                  }
                "
                :loading="auditLoading"
                >{{ auditLoading ? '提交中 ...' : '审核通过' }}</el-button
              >
            </div>
          </div>
        </div>
        <el-tabs type="border-card" v-model="currentTab">
          <!-- 基础信息 -->
          <el-tab-pane label="基础信息" name="0">
            <div class="detailSection">
              <ul class="list mt-16">
                <li class="item">
                  <div class="tips">ID：</div>
                  <div class="value">{{ auditForm.id | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">用户ID：</div>
                  <div class="value">{{ auditForm.eUserId | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">赛事ID：</div>
                  <div class="value">{{ auditForm.competitionId | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">姓名：</div>
                  <div class="value">{{ auditForm.name | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">手机号：</div>
                  <div class="value">{{ auditForm.phoneNumber | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">邮箱：</div>
                  <div class="value">{{ auditForm.email | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">身份证号：</div>
                  <div class="value">{{ auditForm.idCard | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">企业名称：</div>
                  <div class="value">{{ auditForm.companyName | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">学校名称：</div>
                  <div class="value">{{ auditForm.schoolName | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">认证类型：</div>
                  <div class="value">{{ getapplyTypeListText(auditForm.applyType) }}</div>
                </li>
                <li class="item">
                  <div class="tips">申请状态：</div>
                  <div class="value">{{ getIsApplyText(auditForm.isApply) }}</div>
                </li>
                <li class="item">
                  <div class="tips">报名时间：</div>
                  <div class="value">{{ auditForm.applyTime | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">赛事名称：</div>
                  <div class="value">{{ auditForm.competitionName | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">创建时间：</div>
                  <div class="value">{{ auditForm.createTime | filterEmpty }}</div>
                </li>
                <li class="item">
                  <div class="tips">更新时间：</div>
                  <div class="value">{{ auditForm.updateTime | filterEmpty }}</div>
                </li>
              </ul>
              <div class="list" style="display: block">
                <div class="item">
                  <div class="tips">说明：</div>
                  <div class="value">{{ auditForm.remark | filterEmpty }}</div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 文件信息 -->
          <el-tab-pane label="文件信息" name="2">
            <div class="detailSection">
              <ul class="list mt-16">
                <li class="item">
                  <div class="tips">附件文件：</div>
                  <div class="value">
                    <div v-if="auditForm.fileUrl" class="file-list">
                      <div v-for="(file, index) in getFileList(auditForm.fileUrl)" :key="index" class="file-item">
                        <el-link type="primary" :href="formatFileUrl(file.url)" target="_blank">
                          <i class="el-icon-download"></i>
                          下载文件{{ index + 1 }}
                        </el-link>
                      </div>
                    </div>
                    <span v-else class="text-muted">暂无文件</span>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">身份证正面：</div>
                  <div class="value">
                    <el-image
                      v-if="auditForm.idCardFront"
                      :src="auditForm.idCardFront"
                      style="max-width: 200px; max-height: 150px"
                      :preview-src-list="[auditForm.idCardFront]"
                    />
                    <span v-else class="text-muted">暂无图片</span>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">身份证反面：</div>
                  <div class="value">
                    <el-image
                      v-if="auditForm.idCardEnd"
                      :src="auditForm.idCardEnd"
                      style="max-width: 200px; max-height: 150px"
                      :preview-src-list="[auditForm.idCardEnd]"
                    />
                    <span v-else class="text-muted">暂无图片</span>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">营业执照：</div>
                  <div class="value">
                    <el-image
                      v-if="auditForm.businessLicense"
                      :src="auditForm.businessLicense"
                      style="max-width: 200px; max-height: 150px"
                      :preview-src-list="[auditForm.businessLicense]"
                    />
                    <span v-else class="text-muted">暂无图片</span>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">授权书：</div>
                  <div class="value">
                    <el-image
                      v-if="auditForm.authorization"
                      :src="auditForm.authorization"
                      style="max-width: 200px; max-height: 150px"
                      :preview-src-list="[auditForm.authorization]"
                    />
                    <span v-else class="text-muted">暂无图片</span>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">学生证：</div>
                  <div class="value">
                    <el-image
                      v-if="auditForm.studentCard"
                      :src="auditForm.studentCard"
                      style="max-width: 200px; max-height: 150px"
                      :preview-src-list="[auditForm.studentCard]"
                    />
                    <span v-else class="text-muted">暂无图片</span>
                  </div>
                </li>
              </ul>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <!-- 详情对话框 -->
    <el-dialog :visible.sync="detailDialogVisible" title="申请详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ detailData.email }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detailData.idCard }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{ detailData.companyName }}</el-descriptions-item>
        <el-descriptions-item label="认证类型">
          <el-tag :type="getapplyTypeListType(detailData.applyType)">
            {{ getapplyTypeListText(detailData.applyType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="赛事名称" :span="2">{{ detailData.competitionName }}</el-descriptions-item>
        <el-descriptions-item label="报名时间">{{ detailData.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getAuditStatusType(detailData.checkStatus)">
            {{ getAuditStatusText(detailData.checkStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核说明" :span="2" v-if="detailData.checkRemark">{{
          detailData.checkRemark
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" v-if="detailData.createTime">{{
          detailData.createTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import request from '@/utils/request'; // HTTP请求
import { filterEmpty } from '@/filters'; // 过滤器

export default {
  name: 'AuditPage',
  filters: {
    filterEmpty,
  },
  data() {
    return {
      constants: this.$constants,
      listPram: {
        name: '',
        phoneNumber: '',
        email: '',
        checkStatus: null,
        applyTypeList: null,
        page: 1,
        limit: this.$constants.page.limit[0],
      },
      searchForm: {
        name: '',
        phoneNumber: '',
        email: '',
        checkStatus: null,
        applyTypeList: null,
      },
      listData: { list: [], total: 0 },
      listLoading: true,
      exportLoading: false,

      // 审核对话框
      auditDialogVisible: false,
      auditLoading: false,
      auditForm: {
        id: null,
        competitionId: null,
        name: '',
        phoneNumber: '',
        email: '',
        idCard: '',
        companyName: '',
        applyTypeList: null,
        competitionName: '',
        applyTime: '',
        remark: '',
        checkStatus: null,
        checkRemark: '',
        fileUrl: '',
        idCardFront: '',
        idCardEnd: '',
        businessLicense: '',
        authorization: '',
        studentCard: '',
        eUserId: null,
        isApply: null,
        createTime: '',
        updateTime: '',
        isDel: false,
      },

      // 详情对话框
      detailDialogVisible: false,
      detailData: {},

      // 审核抽屉相关
      direction: 'rtl',
      currentTab: '0',
    };
  },
  created() {
    this.handlerGetListData(this.listPram);
  },
  methods: {
    // 搜索
    handerSearch() {
      console.log('=== 点击查询按钮 ===');
      console.log('当前搜索参数:', this.searchForm);
      this.listPram.page = 1;
      this.listPram.name = this.searchForm.name;
      this.listPram.phoneNumber = this.searchForm.phoneNumber;
      this.listPram.email = this.searchForm.email;
      this.listPram.checkStatus = this.searchForm.checkStatus;
      this.listPram.applyTypeList = this.searchForm.applyTypeList;
      this.handlerGetListData(this.listPram);
    },

    // 导出列表
    handleExport() {
      const params = {
        page: this.listPram.page,
        limit: this.listPram.limit,
        name: this.listPram.name,
        phoneNumber: this.listPram.phoneNumber,
        email: this.listPram.email,
        checkStatus: this.listPram.checkStatus,
        applyTypeList: this.listPram.applyTypeList ? this.listPram.applyTypeList : '1,2,3',
      };
      this.exportLoading = true;
      request
        .get('/admin/apply/audit/excel', { params })
        .then((res) => {
          console.log('导出文件地址:', res);
          const fileUrl = res?.url || res?.data?.url;
          const fileName = res?.fileName || res?.data?.fileName;
          if (!fileUrl) {
            console.error('未获取到导出文件地址', res);
            this.$message.error('导出失败，未获取到文件地址');
            return;
          }
          const filename = fileName || this.extractFileName(fileUrl) || `选手审核_${params.page}.xlsx`;
          console.log('filename', filename);
          this.downloadFileByUrl(fileUrl, filename);
        })
        .catch((err) => {
          console.error('导出失败:', err);
          this.$message.error('导出失败，请稍后重试');
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },

    // 下载文件
    downloadBlobFile(blob, filename) {
      if (!blob) return;
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename || `审核列表_${Date.now()}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    },

    // 新开页面下载文件
    downloadFileByUrl(url, filename) {
      if (!url) return;
      const fullUrl = /^https?:\/\//i.test(url) ? url : `${window.location.origin}${url}`;
      const newTab = window.open(fullUrl, '_blank');
      if (!newTab) {
        console.warn('浏览器阻止了弹窗，尝试使用隐藏链接下载');
        const link = document.createElement('a');
        link.href = fullUrl;
        link.target = '_blank';
        link.rel = 'noopener';
        link.click();
      }
      const showName = filename || this.extractFileName(url);
      this.$message.success(`${showName ? `${showName} ` : ''}正在新页面下载，请稍候`);
    },

    // 从链接中提取文件名
    extractFileName(url) {
      if (!url) return '';
      try {
        const decodedUrl = decodeURIComponent(url);
        const parts = decodedUrl.split('/');
        return parts[parts.length - 1] || '';
      } catch (e) {
        console.warn('文件名解析失败:', e);
        return '';
      }
    },

    // 获取列表数据
    handlerGetListData(pram) {
      console.log('开始调用审核列表接口，参数:', pram);
      this.listLoading = true;

      // 尝试多个可能的API接口
      const apiUrls = ['/admin/apply/audit/page/list', '/admin/apply/audit/list', '/admin/apply/list'];

      this.tryApiCall(apiUrls, 0, pram);
    },

    // 尝试API调用
    tryApiCall(apiUrls, index, pram) {
      if (index >= apiUrls.length) {
        console.error('所有API接口都调用失败，使用模拟数据');
        // 使用模拟数据
        this.loadMockData();
        return;
      }

      const apiUrl = apiUrls[index];
      console.log(`尝试调用API: ${apiUrl}`);

      request
        .get(apiUrl, {
          params: {
            page: pram.page,
            limit: pram.limit,
            name: pram.name,
            phoneNumber: pram.phoneNumber,
            email: pram.email,
            checkStatus: pram.checkStatus,
            applyTypeList: pram.applyTypeList ? pram.applyTypeList : '1,2,3',
          },
        })
        .then((res) => {
          console.log(`API ${apiUrl} 响应:`, res);
          this.listData = {
            list: res.list || res.data?.list || [],
            total: res.total || res.data?.total || 0,
          };
          console.log('审核列表数据:', this.listData);
          console.log('第一条数据示例:', this.listData.list[0]);
          this.listLoading = false;
        })
        .catch((err) => {
          console.error(`API ${apiUrl} 调用失败:`, err);
          // 尝试下一个API
          this.tryApiCall(apiUrls, index + 1, pram);
        });
    },

    // 加载模拟数据
    loadMockData() {
      console.log('加载模拟数据');
      this.listData = {
        list: [
          {
            id: 1,
            applicantName: '张三',
            phone: '13800138001',
            email: 'zhangsan@example.com',
            idCard: '110101199001011234',
            company: '测试公司',
            position: '设计师',
            experience: '5年设计经验',
            checkStatus: null, // null代表未审核
            auditReason: '',
            createTime: '2024-01-01 10:00:00',
            auditTime: '',
          },
          {
            id: 2,
            applicantName: '李四',
            phone: '13800138002',
            email: 'lisi@example.com',
            idCard: '110101199002021234',
            company: '创意公司',
            position: '创意总监',
            experience: '8年创意经验',
            checkStatus: 1, // 1代表审核通过
            auditReason: '审核通过',
            createTime: '2024-01-02 10:00:00',
            auditTime: '2024-01-02 15:00:00',
          },
          {
            id: 3,
            applicantName: '王五',
            phone: '13800138003',
            email: 'wangwu@example.com',
            idCard: '110101199003031234',
            company: '设计工作室',
            position: 'UI设计师',
            experience: '3年UI设计经验',
            checkStatus: 0, // 0代表审核拒绝
            auditReason: '资料不完整',
            createTime: '2024-01-03 10:00:00',
            auditTime: '2024-01-03 16:00:00',
          },
        ],
        total: 3,
      };
      console.log('模拟数据加载完成:', this.listData);
      this.listLoading = false;
    },

    // 获取审核状态类型
    getAuditStatusType(status) {
      const statusMap = {
        null: 'warning', // 待审核 (null代表未审核)
        1: 'success', // 审核通过
        0: 'danger', // 审核拒绝
      };
      return statusMap[status] || 'info';
    },

    // 获取审核状态文本
    getAuditStatusText(status) {
      const statusMap = {
        null: '待审核', // null代表未审核
        1: '审核通过',
        0: '审核拒绝',
      };
      return statusMap[status] || '未审核';
    },

    // 判断审核是否已完成
    isAuditCompleted(status) {
      // 审核通过(1)或审核拒绝(0)都视为已完成
      return status === 1 || status === 0;
    },

    // 获取认证类型文本
    getapplyTypeListText(applyTypeList) {
      // 处理可能的数组或逗号分隔字符串格式
      if (Array.isArray(applyTypeList)) {
        applyTypeList = applyTypeList[0];
      } else if (typeof applyTypeList === 'string' && applyTypeList.includes(',')) {
        applyTypeList = applyTypeList.split(',')[0];
      }
      console.log('applyTypeList', applyTypeList);

      const typeMap = {
        1: '个人',
        2: '企业',
        3: '学生',
      };
      return typeMap[applyTypeList] || '未认证';
    },

    // 获取认证类型标签类型
    getapplyTypeListType(applyTypeList) {
      // 处理可能的数组或逗号分隔字符串格式
      if (Array.isArray(applyTypeList)) {
        applyTypeList = applyTypeList[0];
      } else if (typeof applyTypeList === 'string' && applyTypeList.includes(',')) {
        applyTypeList = applyTypeList.split(',')[0];
      }

      const typeMap = {
        1: 'primary', // 个人 - 蓝色
        2: 'success', // 企业 - 绿色
        3: 'warning', // 学生 - 橙色
      };
      return typeMap[applyTypeList] || 'danger'; // 未认证 - 红色
    },

    // 获取申请状态文本
    getIsApplyText(isApply) {
      const statusMap = {
        1: '审核中',
        2: '审核通过',
        3: '审核不通过',
      };
      return statusMap[isApply] || '未申请';
    },

    // 获取申请状态标签类型
    getIsapplyTypeList(isApply) {
      const typeMap = {
        1: 'warning', // 审核中 - 橙色
        2: 'success', // 审核通过 - 绿色
        3: 'danger', // 审核不通过 - 红色
      };
      return typeMap[isApply] || 'info';
    },

    // 获取文件列表 - 拆分逗号分隔的文件地址
    getFileList(fileUrl) {
      if (!fileUrl) return [];

      // 按英文逗号分隔文件地址
      const urls = fileUrl.split(',').filter((url) => url.trim());

      return urls.map((url, index) => ({
        url: url.trim(),
        name: `文件${index + 1}`, // 默认文件名
      }));
    },

    // 格式化文件URL
    formatFileUrl(url) {
      if (!url) return '';

      // 如果URL包含重复的域名，只保留一个
      if (url.includes('https://toyadmin.reh.cn/https://toyadmin.reh.cn/')) {
        url = url.replace('https://toyadmin.reh.cn/https://toyadmin.reh.cn/', 'https://toyadmin.reh.cn/');
      }

      // 确保URL以 http:// 或 https:// 开头
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        return 'https://' + url;
      }

      return url;
    },

    // 处理操作命令
    handleCommand(command) {
      const { action, row } = command;

      switch (action) {
        case 'detail':
          this.handleDetail(row);
          break;
        case 'audit':
          this.handleAudit(row);
          break;
        case 'reject':
          this.handleReject(row);
          break;
      }
    },

    // 详情
    handleDetail(row) {
      // 调用详情接口获取完整数据
      request
        .get(`/admin/apply/audit/detail/${row.id}`)
        .then((res) => {
          console.log('获取详情成功:', res);
          this.detailData = res.data || res;
          this.detailDialogVisible = true;
        })
        .catch((err) => {
          console.error('获取详情失败:', err);
          this.$message.error('获取详情失败，请稍后重试');
        });
    },

    // 审核
    handleAudit(row) {
      // 检查是否已完成审核
      if (this.isAuditCompleted(row.checkStatus)) {
        this.$message.warning('该申请已完成审核，无法重复操作');
        return;
      }

      this.auditForm = {
        id: row.id,
        competitionId: row.competitionId,
        name: row.name,
        phoneNumber: row.phoneNumber,
        email: row.email,
        idCard: row.idCard,
        companyName: row.companyName,
        applyTypeList: row.applyTypeList,
        competitionName: row.competitionName,
        applyTime: row.applyTime,
        remark: row.remark,
        checkStatus: row.checkStatus,
        checkRemark: row.checkRemark || '',
        fileUrl: row.fileUrl || '',
        idCardFront: row.idCardFront || '',
        idCardEnd: row.idCardEnd || '',
        businessLicense: row.businessLicense || '',
        authorization: row.authorization || '',
        studentCard: row.studentCard || '',
        eUserId: row.eUserId,
        isApply: row.isApply,
        createTime: row.createTime || '',
        updateTime: row.updateTime || '',
        isDel: row.isDel || false,
        schoolName: row.schoolName || '',
      };
      this.currentTab = '0';
      this.auditDialogVisible = true;
    },

    // 拒绝
    handleReject(row) {
      this.auditForm = {
        id: row.id,
        competitionId: row.competitionId,
        name: row.name,
        phoneNumber: row.phoneNumber,
        email: row.email,
        idCard: row.idCard,
        companyName: row.companyName,
        applyTypeList: row.applyTypeList,
        competitionName: row.competitionName,
        applyTime: row.applyTime,
        remark: row.remark,
        checkStatus: row.checkStatus,
        checkRemark: row.checkRemark || '',
        fileUrl: row.fileUrl || '',
        idCardFront: row.idCardFront || '',
        idCardEnd: row.idCardEnd || '',
        businessLicense: row.businessLicense || '',
        authorization: row.authorization || '',
        studentCard: row.studentCard || '',
        eUserId: row.eUserId,
        isApply: row.isApply,
        createTime: row.createTime || '',
        updateTime: row.updateTime || '',
        isDel: row.isDel || false,
      };
      this.currentTab = '0';
      this.auditDialogVisible = true;
    },

    // 提交审核
    submitAudit() {
      // 验证必要字段
      if (!this.auditForm.id) {
        this.$message.error('缺少审核记录ID');
        return;
      }

      if (this.auditForm.checkStatus === null || this.auditForm.checkStatus === undefined) {
        this.$message.error('请选择审核结果');
        return;
      }

      this.auditLoading = true;

      // 根据审核状态选择对应的API接口
      const apiUrl = this.auditForm.checkStatus === 1 ? '/admin/apply/audit/pass' : '/admin/apply/audit/reject';

      // 构建请求参数
      const requestData = {
        id: this.auditForm.id,
        isApply: this.auditForm.checkStatus === 1 ? 2 : 3, // 1-审核中，2-审核通过，3-审核不通过
      };

      // 如果是审核拒绝，添加拒绝原因
      if (this.auditForm.checkStatus === 0 && this.auditForm.checkRemark) {
        requestData.checkRemark = this.auditForm.checkRemark;
      }

      console.log('提交审核请求:', { apiUrl, requestData });

      request
        .post(apiUrl, requestData)
        .then((res) => {
          console.log('审核API响应:', res);
          console.log('响应类型:', typeof res, '是否为null:', res === null);

          // 检查响应是否存在
          if (res === null || res === undefined) {
            console.log('API返回null，视为成功');
            this.$message.success('审核完成');
            this.closeAuditDialog();
            this.handlerGetListData(this.listPram);
            this.auditLoading = false;
            return;
          }

          console.log('响应code:', res.code, '类型:', typeof res.code);

          // 检查响应是否成功
          if (res.code === 200 || res.code === '200' || res.status === 200) {
            this.$message.success(res.message || '审核完成');
            this.closeAuditDialog();
            this.handlerGetListData(this.listPram);
          } else {
            console.error('审核失败，响应code:', res.code);
            this.$message.error(res.message || res.msg || '审核失败');
          }
          this.auditLoading = false;
        })
        .catch((err) => {
          console.error('审核API调用失败:', err);
          this.$message.error('审核失败，请稍后重试');
          this.auditLoading = false;
        });
    },

    // 审核通过
    submitPass() {
      // 使用确认弹窗进行二次确认
      this.$modalSure('确定要通过该申请吗？')
        .then(() => {
          // 设置审核状态为通过并提交
          this.auditForm.checkStatus = 1; // 设置为审核通过
          this.submitAudit();
        })
        .catch(() => {
          console.log('用户取消审核通过');
        });
    },

    // 审核拒绝
    submitReject() {
      // 使用模态提示框让用户输入拒绝原因
      this.$modalPrompt('textarea', '请输入拒绝原因', '')
        .then((reason) => {
          console.log('审核拒绝原因:', reason, typeof reason);
          // 确保reason是字符串
          const reasonText = typeof reason === 'string' ? reason : reason && reason.value ? reason.value : '';

          if (!reasonText || reasonText.trim() === '') {
            this.$message.warning('拒绝原因不能为空');
            return;
          }

          // 设置拒绝原因
          this.auditForm.checkRemark = reasonText.trim();

          // 直接执行审核拒绝，不需要再次确认
          this.auditForm.checkStatus = 0; // 设置为审核拒绝
          this.submitAudit();
        })
        .catch(() => {
          // 用户取消输入拒绝原因
          console.log('用户取消输入拒绝原因');
        });
    },

    // 关闭审核对话框
    closeAuditDialog() {
      this.auditDialogVisible = false;
      this.auditForm = {
        id: null,
        competitionId: null,
        name: '',
        phoneNumber: '',
        email: '',
        idCard: '',
        companyName: '',
        applyTypeList: null,
        competitionName: '',
        applyTime: '',
        remark: '',
        checkStatus: null,
        checkRemark: '',
        fileUrl: '',
        idCardFront: '',
        idCardEnd: '',
        businessLicense: '',
        authorization: '',
        studentCard: '',
        eUserId: null,
        isApply: null,
        createTime: '',
        updateTime: '',
        isDel: false,
      };
      this.$refs.auditForm && this.$refs.auditForm.resetFields();
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.listPram.limit = val;
      this.handlerGetListData(this.listPram);
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listPram.page = val;
      this.handlerGetListData(this.listPram);
    },

    // 重置
    reset() {
      this.searchForm = {
        name: '',
        phoneNumber: '',
        email: '',
        checkStatus: null,
        applyTypeList: null,
      };
      this.listPram = {
        name: '',
        phoneNumber: '',
        email: '',
        checkStatus: null,
        applyTypeList: null,
        page: 1,
        limit: this.$constants.page.limit[0],
      };
      this.handlerGetListData(this.listPram);
    },
  },
};
</script>

<style scoped lang="scss">
.divBox {
  min-height: 100vh;
  position: relative;
  width: 100%;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.selWidth {
  width: 200px;
}

.mt14 {
  margin-top: 14px;
}

.mt20 {
  margin-top: 20px;
}

.mr10 {
  margin-right: 10px;
}

.padding-add {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 审核抽屉样式 */
.infoBox {
  .detailHead {
    padding: 20px;
    border-bottom: 1px solid #e6e6e6;
    background: #f8f9fa;

    .headerBox {
      align-items: center;

      .order_icon {
        width: 50px;
        height: 50px;
        background: #409eff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;

        .iconfont {
          color: #fff;
          font-size: 24px;
        }
      }

      .text {
        flex: 1;

        .title {
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin-bottom: 8px;
        }

        .color-warning {
          color: #e6a23c;
          font-weight: bold;
        }
      }
    }
  }

  .detailSection {
    padding: 20px;

    .list {
      .item {
        display: flex;
        margin-bottom: 15px;
        align-items: flex-start;

        .tips {
          width: 120px;
          color: #666;
          font-weight: 500;
          flex-shrink: 0;
        }

        .value {
          flex: 1;
          color: #333;
          word-break: break-all;
        }
      }
    }
  }
}

.acea-row {
  display: flex;
  align-items: center;

  &.row-between {
    justify-content: space-between;
  }

  &.justify-content {
    gap: 10px;
  }
}

.mr20 {
  margin-right: 20px;
}

.mt-16 {
  margin-top: 16px;
}

// 文件列表样式
.file-list {
  .file-item {
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .el-link {
      display: inline-flex;
      align-items: center;

      .el-icon-download {
        margin-right: 4px;
      }
    }
  }
}

.text-muted {
  color: #999;
  font-size: 12px;
}

// 置灰链接样式
.disabled-link {
  color: #c0c4cc !important;
  text-decoration: none !important;

  &:hover {
    color: #c0c4cc !important;
    text-decoration: none !important;
  }
}
</style>
